import { _decorator, Component, Input, instantiate, Label, Node, Prefab, Sprite, tween } from 'cc';
import { Reward, Http, LoadUrlImg, SucType } from '../../main/lib/Net';
import { BagList } from '../../main/lib/Type';
import { fund } from '../../main/common/fund';
import { Util } from '../../main/lib/Util';
import { BtnType } from '../../main/common/Alert';
import { Main } from '../Main';
import { Shopping } from './Shopping';
const { ccclass, property } = _decorator;

@ccclass('Lottery')
export class Lottery extends Component {
    static I: Lottery = null;
    exit() { this.node.destroy() };
    /**奖盘节点 */
    @property(Node)
    PrizePlate: Node = null;
    /**抽奖券文字 */
    @property([Label])
    cjqLibel: Label[] = [];
    /**结果节点*/
    @property(Node)
    outcome: Node = null;
    @property(Node)
    content: Node = null;
    /**奖品预制体 */
    @property(Prefab)
    prize: Prefab = null;
    //奖品列表数组
    DrawArr: Reward[] = [];
    //奖盘的每个元素间隔距离
    angle: number = 45;
    //节流按钮
    btnbol: boolean = true;
    start() {
        Outcome.content = this.content;
        Outcome.outcome = this.outcome;
        Outcome.prize = this.prize;
        Lottery.I = this;
        this.init()
        this.getnum()
    }
    init() {
        const prizeArr = this.PrizePlate.children;
        new Http<SucType<Reward[]>>(suc => {
            if (suc.code === 0) {
                this.DrawArr = suc.data;//存一个全局变量
                suc.data.forEach((prize, idx) => {
                    const pirzeNode = prizeArr[idx]
                    pirzeNode.children[1].getComponent(Label).string = prize.name;//设置name
                    new LoadUrlImg().getFrame(prize.image).then(frame => {
                        pirzeNode.children[0].getComponent(Sprite).spriteFrame = frame;//设置图片
                    })
                })
            }
            console.log('奖品列表数据', suc)
        }).reward_list()
    }
    /**获取背包奖券数量 */
    getnum() {
        new Http((suc: BagList) => {
            if (suc.code === 0 && suc.data !== null) {
                //在背包里面找到抽奖券的item
                const cjqNode = suc.data.filter(item => item.name === "抽奖券")[0];
                if (cjqNode !== undefined) {
                    //设置抽奖按钮上的label文字
                    this.cjqLibel.forEach(item => item.string = `x${cjqNode.numbs}`)
                }
            }
        }).baglist();
    }
    /**抽奖按钮事件 */
    click({ target }: { target: Node }) {
        if (this.btnbol) {
            this.btnbol = false;
            switch (target.name) {
                case KEYTYPE.once:
                    this.lottery(1)
                    break;
                case KEYTYPE.Ten:
                    this.lottery(10)
                    break;
                case KEYTYPE.share:
                    
                    break;
            }
        }
    }
    /**抽奖开始 */
    lottery(times = 1) {
        let rewArr: Reward[] = [];//抽到奖品的数据
        let rewplayArr: Reward[] = [];//抽到奖品的数据用来播放动画的
        const paly = (reward: Reward) => {
            //刷新一下抽奖券数量
            this.getnum()
            //刷新金币内容
            fund.loadFund()
            //重置抽奖圆盘角度为0
            this.PrizePlate.angle = 0;
            //计算当前的reward在那个角度
            const angle = (reward.id - 1) * this.angle;
            // console.log('奖品的角度为:', angle);
            tween(this.PrizePlate).to(1, { angle: 720 })
                .to(0, { angle: 0 })
                .to(1, { angle: angle })
                .call(() => {
                    // console.log('播放完毕', rewplayArr);
                    if (rewplayArr.length > 0) { //继续抽奖
                        setTimeout(() => {
                            paly(rewplayArr.pop())
                        }, 500);
                    } else {
                        {
                            console.log('抽奖完毕', rewArr);
                            new Outcome(rewArr, () => {
                                this.btnbol = true;
                            });// 显示抽奖结果
                        }
                    }
                }).start()
        }
        new Http<SucType<Reward[]>>(suc => {
            if (suc.code === 0) {
                rewArr = suc.data;
                rewplayArr = suc.data.filter(item => true);
                paly(rewplayArr.pop()) //播放抽奖动画
            } else {
                this.btnbol = true;
                new Util.Alert().ShowAlert({
                    msg: `${suc.msg},前往商城购买？`,
                    cancel: true,
                    confrm: true,
                    callfun: function (type: BtnType, node: Node): void {
                        switch (type) {
                            case BtnType.Confrm:
                                Main.ToggleUI('Shopping', Lottery.I.node.name, true)
                                break;
                        }
                        node.destroy();
                    }
                })
            }
        }).turntableDraw(times)
    }
}
enum KEYTYPE {
    share = '分享免费抽',
    once = '抽1次',
    Ten = '抽10次'
}
class Outcome {
    static outcome: Node;
    static prize: Prefab;
    static content: Node;
    constructor(reward: Reward[], calfun: () => void) {
        const this_ = Outcome;
        this_.content.removeAllChildren()//清空所有子节点
        setTimeout(() => { this_.outcome.active = true; }, 1000);//显示结果面板
        calfun()
        this_.outcome.children[0].children[2].once(Input.EventType.TOUCH_START, () => setTimeout(() => { this_.outcome.active = false }, 500)) //按钮绑定事件
        reward.forEach(prizeData => {
            const prizeNode = instantiate(this_.prize);
            prizeNode.children[3].active = false;
            const prize = prizeNode.children[0];
            const [iconNode, label] = prize.children;
            //加载奖品图标
            new LoadUrlImg().getFrame(prizeData.image).then(frame => {
                iconNode.getComponent(Sprite).spriteFrame = frame
            })
            //设置奖品文字
            label.children[0].getComponent(Label).string = prizeData.name;
            this_.content.addChild(prizeNode);
        })
    }
}